package com.lannuokeji.biz.ac;

import java.util.Collection;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.lannuokeji.base.AController;
import com.lannuokeji.biz.ac.entity.User;
import com.lannuokeji.biz.ac.service.UserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import top.ibase4j.model.Login;
@Api(description="登录相关")
@RestController
@RequestMapping("/ac")
public class LoginController extends AController {

	@Resource
	UserService userService;
	
	@ApiOperation(value = "用户登录")
	@PostMapping("/login")
	public Object login(@RequestBody Login login) {
		// TODO - 应该要先进行数据校验
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(login.getAccount(), login.getPassword());
		try {
			subject.login(token);
			return setSuccessContent("成功");
		} catch (LockedAccountException e) {
			token.clear();
			return setErrorContent("账号被锁定了");
		} catch (AuthenticationException e) {
			token.clear();
			return "authenticationFailed";
		}
	}
	@ApiOperation(value = "用户注册")
	@PostMapping("/register")
	public Object register(HttpServletRequest request, @RequestBody User user) {
		Integer i = userService.save(user);
		System.out.println(i);
		if (i == 1) {
			return setSuccessContent("成功");
		} else {
			return setErrorContent("注册失败");
		}
	}

	@ApiOperation("未登录")
	@GetMapping("/unauthorized")
	public Object unauthorized() {
		return setReturn(LOGIN, "未登录");
	}
}
